import { queryTagList, savePhoto } from "@/api/content/attachment";
import { uploadFile } from "@/api/file";
import { Attachment } from "@/types/content/attachment";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { PlusOutlined } from "@ant-design/icons";
import {
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Spin,
  Upload,
  UploadFile,
} from "antd";
import { useForm } from "antd/es/form/Form";
import { useCallback, useEffect, useState } from "react";
interface Props {
  isModalOpen: boolean;
  optionType: "add" | "edit";
  oldInfo?: Attachment.Row;
  close?: () => void;
  change?: () => void;
}
export default function PhotoAlbumOption(props: Props) {
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [form] = useForm();
  const [tagType, setTagType] = useState(0);
  const [messageApi] = message.useMessage();
  const [tagList, setTagList] = useState<string[]>([]);
  const getTagList = useCallback(async () => {
    const res = await queryTagList("0");
    if (res.code === 200) {
      setTagList(res.data || []);
    }
  }, []);
  const uploadFileInf = async (file: any) => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      const res = await uploadFile(formData);
      const list = [
        ...fileList,
        {
          uid: new Date().getTime().toString(),
          name: String(fileList.length + 1),
          status: "done",
          url: res.data,
        },
      ];
      setFileList(list as UploadFile[]);
    } catch (error) {
      console.error(error);
    }
  };
  /**
   * 添加接口
   * @param data
   */
  const saveInf = async (data: Attachment.Form) => {
    setLoading(true);
    const res = await savePhoto(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("保存成功");
      props.close && props.close();
      props.change && props.change();
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { tag } = values;
      const urls = fileList.map((item) => item.url || "");
      const params = {
        type: "0",
        tag,
        urls,
      };
      saveInf(params);
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  useEffect(() => {
    getTagList();
  }, [getTagList]);
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );
  return (
    <Modal
      title={props.optionType === "add" ? "新增" : "修改"}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          name="PhotoAlbumOption"
          size="middle"
          initialValues={{ tagType: 0 }}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item label="图片" name="urls">
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              action="#"
              fileList={fileList}
              customRequest={(file) => uploadFileInf(file.file)}
              onRemove={(file) => {
                file.url && deleteFileInf(file.url);
                setFileList(fileList.filter((item) => item.url !== file.url));
              }}
            >
              {uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item label="标签类型" name="tagType">
            <Radio.Group
              onChange={(e) => {
                setTagType(e.target.value);
              }}
              value={tagType}
            >
              <Radio value={0}>历史标签</Radio>
              <Radio value={1}>新标签</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item<Attachment.Form>
            name="tag"
            label="标签"
            rules={[{ required: true, message: "标签不能为空" }]}
          >
            {tagType === 1 ? (
              <Input />
            ) : (
              <Select
                placeholder="请选择"
                style={{ width: 180 }}
                allowClear
                size="middle"
              >
                {tagList.map((item) => (
                  <Select.Option value={item} key={item}>
                    {item}
                  </Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}
